//
//  AppDelegate+JPush.m
//  OwnerAPP
//
//  Created by apple on 16/12/2.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "AppDelegate+JPush.h"
#import "WorkViewController.h"
//极光推送
#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

#import "EBForeNotification.h"

@implementation AppDelegate (JPush)

#pragma mark - 设置极光推送
-(void)setJPUSWithApplication:(UIApplication *)application Options:(NSDictionary *)launchOptions{
    
    //    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSString *advertisingId = nil;
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        DLog(@"222222");
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            DLog(@"registrationID获取成功：%@",registrationID);
            
        }
        else{
            DLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotification) {  //当应用未启动时，收到通知走着
        DLog(@"当应用未启动时，收到通知走着:%@", [self logDic:launchOptions]);
        [JPUSHService handleRemoteNotification:remoteNotification];
        [JPUSHService setBadge:0];
        
    
    }
    
    //接收APP在线时点击推送信息通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pageJumpWithNSNotification:) name:EBBannerViewDidClick object:nil];
    
   // 接收自定义推送消息
//        NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
//        [defaultCenter addObserver:self
//                          selector:@selector(networkDidReceiveMessage:)
//                              name:kJPFNetworkDidReceiveMessageNotification
//                            object:nil];
    
}
//- (void)networkDidReceiveMessage:(NSNotification *)notification{
//    NSDictionary *userInfo = [notification userInfo];
//    DLog(@"自定义推送消息：%@",userInfo);
//}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    DLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    DLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
#endif
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    //点击推送消息执行方法
    DLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
        //界面进行跳转
        [self goToMssageViewControllerWith:application Notification:userInfo];
    }
    
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    //    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
    DLog(@"点击本地推送消息%@%@",[notification userInfo],notification.userInfo);
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        DLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
    }
    else {
        // 判断为本地通知
        DLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        //点击推送消息执行方法
        
        DLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
        //界面进行跳转
          [self goToMssageViewControllerWith:nil Notification:userInfo];
    }
    else {
        // 判断为本地通知
        DLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif

- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

-(void)goToMssageViewControllerWith:(UIApplication *) application Notification:(NSDictionary *)userInfo{
    
    if(application.applicationState == UIApplicationStateActive){ //这里写APP正在运行时，推送过来消息的处理
        //        DLog(@"%@",userInfo);
        
        if([[UIDevice currentDevice].systemVersion floatValue]<10.0 ){//iOS 10一下
            NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
            [pushJudge setObject:userInfo forKey:@"userInfo"];
            [EBForeNotification handleRemoteNotification:userInfo soundID:1312 isIos10:NO];
        }else{
            [self pageJumpWith:userInfo];
        }
        
    }else if (application.applicationState == UIApplicationStateInactive){//APP在后台运行，推送过来消息的处理
        DLog(@"APP在后台运行，推送过来消息的处理");
        [self pageJumpWith:userInfo];
    }else if (application.applicationState == UIApplicationStateBackground){//APP没有运行，推送过来消息的处理
        DLog(@"APP没有运行，推送过来消息的处理");
        [self pageJumpWith:userInfo];
    }
}
-(void)pageJumpWithNSNotification:(NSNotification*)notifi{
    NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
    
    [self pageJumpWith:[pushJudge objectForKey:@"userInfo"]];
}
-(void)pageJumpWith:(NSDictionary *) userInfo{
    
    NSString * type = userInfo[@"type"];
    if([type integerValue] == JPushType_MyNew)
    {
        //将字段存入本地，用于判断是点击推送消息进行跳转还是正常跳转
        NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
        [pushJudge setObject:Push forKey:Push];
        [pushJudge synchronize];
        WorkViewController * myWorkVC = [[WorkViewController alloc] init];
        BHNavigationController * bhNav = [[BHNavigationController alloc] initWithRootViewController:myWorkVC];
        [self.window.rootViewController presentViewController:bhNav animated:YES completion:nil];
        
    }else if ([type integerValue] == JPushType_PropertyNotice)
    {
        //将字段存入本地，用于判断是点击推送消息进行跳转还是正常跳转
        //        NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
        //        [pushJudge setObject:Push forKey:Push];
        //        [pushJudge synchronize];
        //
        //        PropertyNoticeViewController * propertNVC = [[PropertyNoticeViewController alloc] init];
        //        propertNVC.notictType = Nontict_Type_Emergency;
        //        BHNavigationController * bhNav = [[BHNavigationController alloc] initWithRootViewController:propertNVC];
        //        [self.window.rootViewController presentViewController:bhNav animated:YES completion:nil];
    }
}
@end
